//
//  HSLDiscoverSearchView.swift
//  HSLMicroBlog
//
//  Created by mac on 15/12/12.
//  Copyright © 2015年 HSL. All rights reserved.
//

import UIKit

@IBDesignable
class HSLDiscoverSearchView: UIView, UITextFieldDelegate {

    @IBOutlet weak var textField: UITextField! //搜索框
    @IBOutlet weak var cancleBtn: UIButton! //取消按钮
    @IBOutlet weak var trailingConstraint: NSLayoutConstraint! //输入框右侧约束
    
    //快速构造函数,从xib加载view
    class func searchView() -> HSLDiscoverSearchView {
        return (NSBundle.mainBundle().loadNibNamed("HSLDiscoverSearchView", owner: nil, options: nil).last! as! HSLDiscoverSearchView)
    }
    
    //布局控件
    override func awakeFromNib() {
        //设置输入框左侧图标
        let leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        leftView.frame = CGRectMake(0, 0, frame.height, frame.height)
        leftView.contentMode = .Center
        textField.leftView = leftView
        textField.leftViewMode = .Always
    }
    
    //点击取消按钮触发的事件
    @IBAction func cancleBtnDidClick() {
        textField.resignFirstResponder()
        trailingConstraint.constant = 0
        UIView.animateWithDuration(0.25) { () -> Void in
            self.textField.layoutIfNeeded()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    // MARK: - UITextFieldDelegate
    
    func textFieldDidBeginEditing(textField: UITextField) {
        trailingConstraint.constant = cancleBtn.frame.width
        UIView.animateWithDuration(0.25) { () -> Void in
            self.textField.layoutIfNeeded()
        }
    }
    

}
